import { Component, OnInit } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { mobileValidate } from '@core/util/formControl-validate-utils';
import { AgentService } from '@core/routes-services/agent.service';

@Component({
  selector: 'app-agent-recharge',
  templateUrl: './agent-recharge.component.html',
})
export class AgentRechargeComponent implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = false;

  levelOptions: any [] = [];

  levelInfo: any = {};

  applicationId :any = null;
  applicationIn:any = null;
  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              private agentService: AgentService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    let totalIn = null;
    if(this.applicationId){
      totalIn = this.applicationIn;
    }else {
      this.levelInfo = this.levelOptions.find((t) => t.id == this.entity.levelId);
      totalIn = this.levelInfo.promotion
    }
    this.validateForm = this.fb.group({
      name: [this.entity.name, [Validators.required, Validators.maxLength(30)]],
      phone: [this.entity.phone, [Validators.required, mobileValidate]],
      levelId: [this.entity.levelId, [Validators.required]],
      status: [1, [Validators.required]],//充值后默认给设置成1-激活启用
      totalIn: [totalIn, [Validators.required]],
    });
  }


  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      if(this.validateForm.value.totalIn < 0 && this.validateForm.value.totalIn < -this.entity.balance ){
        this.message.warning("当前余额不足以扣除您输入的充值金额");
        return;
      }
      this.isLoading = true;
      if(this.applicationId){
        this.agentService.payApplication(this.entity.id,this.applicationId, this.validateForm.value).then((res) => {
          if (res.status.toString().startsWith('20')) {
            this.modal.close(true);
          } else {
            this.message.warning(res.message);
          }
          this.isLoading = false;
        }, error => {
          this.message.error(error.message ? error.message : error.error);
          this.isLoading = false;
        });
      }else {
        this.agentService.recharge(this.entity.id, this.validateForm.value).then((res) => {
          if (res.status.toString().startsWith('20')) {
            this.modal.close(true);
          } else {
            this.message.warning(res.message);
          }
          this.isLoading = false;
        }, error => {
          this.message.error(error.message ? error.message : error.error);
          this.isLoading = false;
        });
      }

    }
  }

  close() {
    this.modal.destroy();
  }
}
